<!--
使用antd原生Form生成 详细用法参考ant-design-vue Form组件文档
vscode默认配置文件会自动格式化/移除未使用依赖
-->
<script setup lang="ts">
import type { RuleObject } from 'ant-design-vue/es/form';

import type { SupplementaryPickupRecordForm } from '#/api/hm/supplementaryPickupRecord/model';

import { computed, ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';
import { $t } from '@vben/locales';
import { cloneDeep } from '@vben/utils';

import {
  DatePicker,
  Form,
  FormItem,
  Input,
  RadioGroup,
  Textarea,
} from 'ant-design-vue';
import { pick } from 'lodash-es';

import {
  supplementaryPickupRecordAdd,
  supplementaryPickupRecordInfo,
  supplementaryPickupRecordUpdate,
} from '#/api/hm/supplementaryPickupRecord';

const emit = defineEmits<{ reload: [] }>();

const isUpdate = ref(false);
const title = computed(() => {
  return isUpdate.value ? $t('pages.common.edit') : $t('pages.common.add');
});

/**
 * 定义默认值 用于reset
 */
const defaultValues: Partial<SupplementaryPickupRecordForm> = {
  supplementaryPickupId: undefined,
  originalSaleId: undefined,
  originalProductId: undefined,
  originalProductName: undefined,
  originalUnfulfilledQuantity: undefined,
  supplementaryProductId: undefined,
  supplementaryProductName: undefined,
  supplementaryQuantity: undefined,
  pickupTime: undefined,
  pickupDeptId: undefined,
  pickupDeptName: undefined,
  operatorId: undefined,
  operatorName: undefined,
  reason: undefined,
  proofFiles: undefined,
  status: undefined,
};

/**
 * 表单数据ref
 */
const formData = ref(defaultValues);

type AntdFormRules<T> = Partial<Record<keyof T, RuleObject[]>> & {
  [key: string]: RuleObject[];
};
/**
 * 表单校验规则
 */
const formRules = ref<AntdFormRules<SupplementaryPickupRecordForm>>({
  originalSaleId: [{ required: true, message: '原始销售订单ID不能为空' }],
  originalProductId: [
    { required: true, message: '原始订单中未提货的产品ID不能为空' },
  ],
  originalUnfulfilledQuantity: [
    { required: true, message: '原始订单中未提货时剩余的数量不能为空' },
  ],
  supplementaryProductId: [
    { required: true, message: '实际补充提货的产品ID不能为空' },
  ],
  supplementaryQuantity: [
    { required: true, message: '实际补充提货的数量不能为空' },
  ],
  pickupTime: [{ required: true, message: '补充提货时间不能为空' }],
});

/**
 * useForm解构出表单方法
 */
const { validate, validateInfos, resetFields } = Form.useForm(
  formData,
  formRules,
);

const [BasicModal, modalApi] = useVbenModal({
  class: 'w-[550px]',
  fullscreenButton: false,
  closeOnClickModal: false,
  onClosed: handleCancel,
  onConfirm: handleConfirm,
  onOpenChange: async (isOpen) => {
    if (!isOpen) {
      return null;
    }
    modalApi.modalLoading(true);

    const { id } = modalApi.getData() as { id?: number | string };
    isUpdate.value = !!id;

    if (isUpdate.value && id) {
      const record = await supplementaryPickupRecordInfo(id);
      // 只赋值存在的字段
      const filterRecord = pick(record, Object.keys(defaultValues));
      formData.value = filterRecord;
    }

    modalApi.modalLoading(false);
  },
});

async function handleConfirm() {
  try {
    modalApi.modalLoading(true);
    await validate();
    // 可能会做数据处理 使用cloneDeep深拷贝
    const data = cloneDeep(formData.value);
    await (isUpdate.value
      ? supplementaryPickupRecordUpdate(data)
      : supplementaryPickupRecordAdd(data));
    emit('reload');
    await handleCancel();
  } catch (error) {
    console.error(error);
  } finally {
    modalApi.modalLoading(false);
  }
}

async function handleCancel() {
  modalApi.close();
  formData.value = defaultValues;
  resetFields();
}
</script>

<template>
  <BasicModal :title="title">
    <Form :label-col="{ span: 4 }">
      <FormItem label="原始销售订单ID" v-bind="validateInfos.originalSaleId">
        <Input
          v-model:value="formData.originalSaleId"
          :placeholder="$t('ui.formRules.required')"
        />
      </FormItem>
      <FormItem
        label="原始订单中未提货的产品ID"
        v-bind="validateInfos.originalProductId"
      >
        <Input
          v-model:value="formData.originalProductId"
          :placeholder="$t('ui.formRules.required')"
        />
      </FormItem>
      <FormItem
        label="原始订单中未提货的产品名称 (冗余)"
        v-bind="validateInfos.originalProductName"
      >
        <Input
          v-model:value="formData.originalProductName"
          :placeholder="$t('ui.formRules.required')"
        />
      </FormItem>
      <FormItem
        label="原始订单中未提货时剩余的数量"
        v-bind="validateInfos.originalUnfulfilledQuantity"
      >
        <Input
          v-model:value="formData.originalUnfulfilledQuantity"
          :placeholder="$t('ui.formRules.required')"
        />
      </FormItem>
      <FormItem
        label="实际补充提货的产品ID"
        v-bind="validateInfos.supplementaryProductId"
      >
        <Input
          v-model:value="formData.supplementaryProductId"
          :placeholder="$t('ui.formRules.required')"
        />
      </FormItem>
      <FormItem
        label="实际补充提货的产品名称 (冗余)"
        v-bind="validateInfos.supplementaryProductName"
      >
        <Input
          v-model:value="formData.supplementaryProductName"
          :placeholder="$t('ui.formRules.required')"
        />
      </FormItem>
      <FormItem
        label="实际补充提货的数量"
        v-bind="validateInfos.supplementaryQuantity"
      >
        <Input
          v-model:value="formData.supplementaryQuantity"
          :placeholder="$t('ui.formRules.required')"
        />
      </FormItem>
      <FormItem label="补充提货时间" v-bind="validateInfos.pickupTime">
        <!-- 需要自行调整参数 -->
        <DatePicker
          v-model:value="formData.pickupTime"
          format="YYYY-MM-DD HH:mm:ss"
          value-format="YYYY-MM-DD HH:mm:ss"
        />
      </FormItem>
      <FormItem label="提货店铺ID" v-bind="validateInfos.pickupDeptId">
        <Input
          v-model:value="formData.pickupDeptId"
          :placeholder="$t('ui.formRules.required')"
        />
      </FormItem>
      <FormItem
        label="提货店铺名称 (冗余)"
        v-bind="validateInfos.pickupDeptName"
      >
        <Input
          v-model:value="formData.pickupDeptName"
          :placeholder="$t('ui.formRules.required')"
        />
      </FormItem>
      <FormItem label="操作人ID" v-bind="validateInfos.operatorId">
        <Input
          v-model:value="formData.operatorId"
          :placeholder="$t('ui.formRules.required')"
        />
      </FormItem>
      <FormItem label="操作人姓名 (冗余)" v-bind="validateInfos.operatorName">
        <Input
          v-model:value="formData.operatorName"
          :placeholder="$t('ui.formRules.required')"
        />
      </FormItem>
      <FormItem
        label="补充提货原因 (例如：原产品缺货，客户同意更换)"
        v-bind="validateInfos.reason"
      >
        <Textarea
          v-model:value="formData.reason"
          :placeholder="$t('ui.formRules.required')"
          :rows="4"
        />
      </FormItem>
      <FormItem label="证明材料" v-bind="validateInfos.proofFiles">
        <Textarea
          v-model:value="formData.proofFiles"
          :placeholder="$t('ui.formRules.required')"
          :rows="4"
        />
      </FormItem>
      <FormItem label="状态" v-bind="validateInfos.status">
        <RadioGroup
          option-type="button"
          button-style="solid"
          v-model:value="formData.status"
          :options="[]"
        />
      </FormItem>
    </Form>
  </BasicModal>
</template>
